package ch.app.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@Controller
public class TestJedis {

	@Autowired
	JedisPool jedisPool;
	
	@RequestMapping(name = "jedis")
	@ResponseBody
	public String set() {
		Jedis jedis = jedisPool.getResource();

		int expiredTime = 5;
		int timeoutTime = 3;
		new Thread() {
			@Override
			public void run() {
				TestJedis testJedis = new TestJedis();
				long result = 0;

				while (result != 1) {
					result = testJedis.lock(Thread.currentThread().getName(), jedisPool);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread name:" + Thread.currentThread().getName() + ", lock status:" + result);
				}
			}
		}.start();

		new Thread() {
			@Override
			public void run() {
				TestJedis testJedis = new TestJedis();
				long result = 0;

				while (result != 1) {
					result = testJedis.lock(Thread.currentThread().getName(), jedisPool);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread name:" + Thread.currentThread().getName() + ", lock status:" + result);
				}
			}
		}.start();



        return "success";
    }

	public long lock(String threadName, JedisPool jedisPool) {
		Jedis jedis = jedisPool.getResource();
		String lockKey = "lockKey";
		String lockValue = "lockValue";
		int expireTime = 5;

		long lock = jedis.setnx(lockKey, lockValue);
		if(lock == 1){
			jedis.expire(lockKey, expireTime);
			System.out.println(threadName + ": get lock success");
		} else {
			System.out.println(threadName + ": get lock failed");
		}

		return lock;
	}
}